<template>
  <div id="map-container">
    <div id="map"></div>
  </div>
</template>

<script>
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet-velocity/dist/leaflet-velocity.css';
import 'leaflet-velocity/dist/leaflet-velocity';
import 'leaflet.tilelayer.colorfilter'; // 引入灰度滤镜插件
import HeatmapOverlay from 'leaflet-heatmap'; // 引入leaflet-heatmap

import jsonData from '/src/data/wind-global.json';
import heatData from '/src/data/heat-data.json'

export default {
  name: 'WeatherMap',
  data() {
    return {
      map: null,
      heatLayer: null,
      velocityLayer: null,
      // 江苏省边界坐标
      jiangsuBounds: [
        [60, 140],  // 东北坐标
        [10, 80] // 西南坐标
      ],
      // 风场数据
      windData: {},
      // 模拟江苏省主要城市气温数据
      temperatureData : {
        max: 26, // 最高温度
        min: 17, // 最低温度
        data: heatData.map(item => ({
          lat: item[0],
          lng: item[1],
          value: item[2]
        }))
        // data: [
        //   // 南京
        //   { lat: 32.0603, lng: 118.7969, value: 38 },
        //   // 苏州
        //   { lat: 31.2989, lng: 120.5853, value: 36 },
        //   // 无锡
        //   { lat: 31.4907, lng: 120.3123, value: 35 },
        //   // 常州
        //   { lat: 31.8107, lng: 119.9736, value: 34 },
        //   // 徐州
        //   { lat: 34.2610, lng: 117.1855, value: 37 },
        //   // 南通
        //   { lat: 32.0147, lng: 120.8564, value: 33 },
        //   // 连云港
        //   { lat: 34.5967, lng: 119.2226, value: 32 },
        //   // 淮安
        //   { lat: 33.6104, lng: 119.0159, value: 33 },
        //   // 盐城
        //   { lat: 33.3477, lng: 120.1636, value: 32 },
        //   // 扬州
        //   { lat: 32.3932, lng: 119.4129, value: 34 },
        //   // 镇江
        //   { lat: 32.1878, lng: 119.4528, value: 33 },
        //   // 泰州
        //   { lat: 32.4558, lng: 119.9257, value: 32 },
        //   // 宿迁
        //   { lat: 33.9619, lng: 118.2969, value: 35 }
        // ]
      },
      // 热力图配置
      heatmapConfig: {
        radius: 0.25,
        maxOpacity: 0.36,
        scaleRadius: true,
        useLocalExtrema: false,
        latField: 'lat',
        lngField: 'lng',
        valueField: 'value',
        gradient: {
          '0.1': 'rgba(238, 238, 238, 0.92)',    // 低温区域为蓝色
          '0.2': 'rgba(255, 170, 255, 0.92)',    // 较低温区域为青色
          '0.3': 'rgba(145, 9, 145, 0.92)',    // 中等温度为绿色
          '0.35': 'rgba(36, 24, 106, 0.92)',  // 较高温度为黄色
          '0.4': 'rgba(85, 78, 177, 0.92)',  // 较高温度为黄色
          '0.45': 'rgba(62, 121, 198, 0.92)',  // 较高温度为黄色
          '0.5': 'rgba(75, 182, 152, 0.92)',     // 高温区域为红色
          '0.55': 'rgba(89, 208, 73, 0.92)',     // 高温区域为红色
          '0.6': 'rgba(190, 228, 61, 0.92)',     // 高温区域为红色
          '0.65': 'rgba(235, 215, 53, 0.92)',     // 高温区域为红色
          '0.7': 'rgba(234, 164, 62, 0.92)',     // 高温区域为红色
          '0.75': 'rgba(229, 109, 83, 0.92)',     // 高温区域为红色
          '0.8': 'rgba(190, 48, 102, 0.92)',     // 高温区域为红色
          '0.85': 'rgb(107, 21, 39)',     // 高温区域为红色
          '0.9': 'rgb(43, 0, 1)',     // 高温区域为红色
        }
      }
    };
  },
  mounted() {
    this.initMap();
    this.addHeatLayer();
    this.generateWindData();
    this.addVelocityLayer();

    // 监听缩放结束事件
    this.map.on('zoomend', () => {
      const zoomLevel = this.map.getZoom();
      console.log('当前缩放级别:', zoomLevel);
    });
  },
  methods: {
    initMap() {
      // 初始化地图，以江苏省为中心
      this.map = L.map('map', {
        center: [32.5, 119.5],
        zoom: 8,
        minZoom: 5,
        maxZoom: 10,
        maxBounds: this.jiangsuBounds,
        maxBoundsViscosity: 1.0
      });

      let myFilter = [
        'blur:0px',
        'brightness:100%',
        'contrast:100%',
        'grayscale:100%',
        'hue:0deg',
        'opacity:100%',
        'invert:0%',
        'saturate:0%',
        'sepia:0%'
      ];

      // 添加底图
      L.tileLayer.colorFilter('https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        filter: myFilter
      }).addTo(this.map);
    },
    addHeatLayer() {
      // 移除旧的热力图层（如果存在）
      if (this.heatLayer) {
        this.map.removeLayer(this.heatLayer);
      }


      // 创建新的热力图层
      this.heatLayer = new HeatmapOverlay(this.heatmapConfig);
      this.heatLayer.setData(this.temperatureData);
      this.heatLayer.addTo(this.map);

      // 添加图例
      this.addLegend();
    },
    // 生成模拟风场数据
    generateWindData() {
      this.windData = jsonData
    },
    // 添加风场图层
    addVelocityLayer() {
      // 移除旧的风场图层（如果存在）
      if (this.velocityLayer) {
        this.map.removeLayer(this.velocityLayer);
      }

      // 创建新的风场图层
      this.velocityLayer = L.velocityLayer({
        displayValues: true,
        displayOptions: {
          velocityType: 'GBR Wind',
          displayPosition: 'bottomleft',
          displayEmptyString: 'No wind data'
        },
        data: this.windData,
        minVelocity: 0,
        maxVelocity: 10,
        velocityScale: 0.005,
        lineWidth: 2,
        particleAge: 30,
        particleMultiplier: 1 / 2000,
        colorScale: ['rgb(255,255,255)', 'rgb(0,255,255)', 'rgb(0,191,255)',
          'rgb(0,127,255)', 'rgb(0,63,255)', 'rgb(0,0,255)']
      }).addTo(this.map);
    },
    addLegend() {
      const legend = L.control({position: 'bottomright'});

      legend.onAdd = () => {
        const div = L.DomUtil.create('div', 'info legend');
        div.innerHTML = '<h4>气温 (°C)</h4>';

        // 根据 heatmapConfig 的 gradient 和 temperatureData 的 min、max 生成气温图例
        const gradientKeys = Object.keys(this.heatmapConfig.gradient).map(Number).sort((a, b) => a - b);
        const min = this.temperatureData.min;
        const max = this.temperatureData.max;
        const range = max - min;
        gradientKeys.forEach((key, index) => {
          const color = this.heatmapConfig.gradient[key];
          debugger;
          const tempValue = min + range * key;
          const nextKey = gradientKeys[index + 1];
          const nextTempValue = nextKey ? min + range * nextKey : max;
          div.innerHTML += `<i style="background:${color};color: white">${tempValue.toFixed(1)}&ndash;${nextTempValue.toFixed(1)}</i> <br>`;
        });

        // 风场图例
        div.innerHTML += '<h4 style="margin-top:10px;">风速 (m/s)</h4>';
        div.innerHTML += '<div class="wind-legend"><span>0</span><span>5</span><span>10+</span></div>';

        return div;
      };

      legend.addTo(this.map);
    },
    // 初始化地名标记
    initCityMarkers() {
      this.clearCityMarkers();

      // 创建地级市标记
      this.citiesData.prefectureCities.forEach(city => {
        const marker = this.createCityMarker(city.name, city.lat, city.lng, 'prefecture');
        this.cityMarkers.prefecture.push(marker);
      });

      // 创建县级市标记
      this.citiesData.countyCities.forEach(city => {
        const marker = this.createCityMarker(city.name, city.lat, city.lng, 'county');
        this.cityMarkers.county.push(marker);
      });

      this.handleZoomChange();
    },
    // 创建地名标记
    createCityMarker(name, lat, lng, type) {
      const markerHtml = `
        <div class="city-marker ${type}" style="background-color: black; color: white;
               padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 12px;">
          ${name}
        </div>
      `;

      const marker = L.marker([lat, lng], {
        icon: L.divIcon({
          html: markerHtml,
          className: 'city-marker-icon',
          iconSize: [100, 30],
          iconAnchor: [50, 15],
          popupAnchor: [0, -15]
        }),
        interactive: true
      }).addTo(this.map);

      marker.on('click', () => {
        console.log(`点击城市: ${name}`);
        console.log(`经纬度: ${lng}, ${lat}`);
      });

      return marker;
    },
    // 清除所有地名标记
    clearCityMarkers() {
      this.cityMarkers.prefecture.forEach(marker => {
        if (marker && this.map) {
          this.map.removeLayer(marker);
        }
      });
      this.cityMarkers.county.forEach(marker => {
        if (marker && this.map) {
          this.map.removeLayer(marker);
        }
      });
      this.cityMarkers.prefecture = [];
      this.cityMarkers.county = [];
    },
    // 处理地图缩放变化
    handleZoomChange() {
      const currentZoom = this.map.getZoom();
      this.clearCityMarkers();

      if (currentZoom >= this.zoomLevels.showCounty) {
        // 显示地级市和县级市
        this.citiesData.prefectureCities.forEach(city => {
          const marker = this.createCityMarker(city.name, city.lat, city.lng, 'prefecture');
          this.cityMarkers.prefecture.push(marker);
        });
        this.citiesData.countyCities.forEach(city => {
          const marker = this.createCityMarker(city.name, city.lat, city.lng, 'county');
          this.cityMarkers.county.push(marker);
        });
      } else if (currentZoom >= this.zoomLevels.showPrefecture) {
        // 只显示地级市
        this.citiesData.prefectureCities.forEach(city => {
          const marker = this.createCityMarker(city.name, city.lat, city.lng, 'prefecture');
          this.cityMarkers.prefecture.push(marker);
        });
      }
    }
  }
};
</script>

<style scoped>
#map-container {
  width: 100%;
  height: 100vh;
}

#map {
  width: 100%;
  height: 100%;
}

/* 图例样式 */
.info {
  padding: 6px 8px;
  font: 14px/16px Arial, Helvetica, sans-serif;
  background: white;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}

.legend {
  line-height: 18px;
  color: #555;
}

.legend i {
  width: 18px;
  height: 18px;
  float: left;
  margin-right: 8px;
  opacity: 0.7;
}

/* 风场图例样式 */
.wind-legend {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 5px;
}

.wind-legend span {
  font-size: 12px;
}

/* 地名标记样式 */
.city-marker-icon {
  pointer-events: auto;
}

.city-marker {
  text-align: center;
  white-space: nowrap;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
}

.city-marker.prefecture {
  background-color: black;
}

.city-marker.county {
  background-color: rgba(0, 0, 0, 0.8);
}
</style>
